﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace cry
{
    internal class CryWork
    {
        public static object privatekey { get; private set; }
        public static object publickey { get; private set; }

        internal static void Init()
        {
            //RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
            // privatekey = oRSA.ToXmlString(true);//私钥 
            // publickey = oRSA.ToXmlString(false);//公钥 
            //using (System.IO.StreamWriter file = new System.IO.StreamWriter("privatekey.txt", true))
            //{
            //    file.WriteLine(privatekey);// 直接追加文件末尾，换行 
            //}
            //using (System.IO.StreamWriter file = new System.IO.StreamWriter( "publickey.txt", true))
            //{
            //    file.WriteLine(publickey);// 直接追加文件末尾，换行 
            //}
        }


       static private string Getcy(string file)
        {
            string xxx = "";
            if (File.Exists(file))
            {
                StreamReader sRead = new StreamReader(file/*.Replace(".tmp", ".txt")*/);
                xxx = sRead.ReadToEnd();
                sRead.Close();
                return xxx;
            }
            return null;
        }

       static private void EncryptProcessmk(string privatekey,string data, string publickeymk) {
            byte[] messagebytes = Encoding.UTF8.GetBytes(data);
            RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
            oRSA3.FromXmlString(privatekey);
            byte[] SignBytes = oRSA3.SignData(messagebytes, "SHA1");

            using (System.IO.StreamWriter objwrite = new System.IO.StreamWriter("mi.txt", true))
            {
                objwrite.BaseStream.Write(SignBytes, 0, SignBytes.Length);
                objwrite.Flush();
            }

            //using (System.IO.StreamReader objReade = new System.IO.StreamReader("mi.txt", true))
            //{
            //    objReade.BaseStream.Write(SignBytes, 0, SignBytes.Length);
            //    objwrite.Flush();
            //}

            FileStream fileStream = new FileStream("mi.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            // 读取文件的 byte[] 
            byte[] SignBytesRead = new byte[fileStream.Length];
            fileStream.Read(SignBytesRead, 0, SignBytesRead.Length);
            fileStream.Close();


            RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
            oRSA4.FromXmlString(publickeymk);
            bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", SignBytesRead);

        }


       static private void DecryptProcessMK()
        {
            //公钥验证 
            //RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
            //oRSA4.FromXmlString(publickey);
            //bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", AOutput);
        }

        //  static  System.IO.StreamWriter objwrite = new System.IO.StreamWriter("mi.txt", false);

        /* 
                  加密过程,其中d、n是RSACryptoServiceProvider生成的D、Modulus 
                 */
        private string EncryptProcess(string source, string d, string n)
        {
            byte[] N = Convert.FromBase64String(n);
            byte[] D = Convert.FromBase64String(d);
            BigInteger biN = new BigInteger(N);
            BigInteger biD = new BigInteger(D);
            return EncryptString(source, biD, biN);
        }

        /* 
                 解密过程,其中e、n是RSACryptoServiceProvider生成的Exponent、Modulus 
                */
        private string DecryptProcess(string source, string e, string n)
        {
            byte[] N = Convert.FromBase64String(n);
            byte[] E = Convert.FromBase64String(e);
            BigInteger biN = new BigInteger(N);
            BigInteger biE = new BigInteger(E);
            return DecryptString(source, biE, biN);
        }


        private string EncryptString(string source, BigInteger d, BigInteger n)
        {
            int len = source.Length;
            int len1 = 0;
            int blockLen = 0;
            if ((len % 128) == 0)
                len1 = len / 128;
            else
                len1 = len / 128 + 1;
            string block = "";
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < len1; i++)
            {
                if (len >= 128)
                    blockLen = 128;
                else
                    blockLen = len;
                block = source.Substring(i * 128, blockLen);
                byte[] oText = System.Text.Encoding.Default.GetBytes(block);
                BigInteger biText = new BigInteger(oText);
                BigInteger biEnText = biText.modPow(d, n);
                string temp = biEnText.ToHexString();
                result.Append(temp).Append("@");
                len -= blockLen;
            }
            return result.ToString().TrimEnd('@');
        }
        private string DecryptString(string source, BigInteger e, BigInteger n)
        {
            StringBuilder result = new StringBuilder();
            string[] strarr1 = source.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < strarr1.Length; i++)
            {
                string block = strarr1[i];
                BigInteger biText = new BigInteger(block, 16);
                BigInteger biEnText = biText.modPow(e, n);
                string temp = System.Text.Encoding.Default.GetString(biEnText.getBytes());
                result.Append(temp);
            }
            return result.ToString();
        }

        internal static void Test1()
        {
            byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗");
            RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
            string privatekey = oRSA.ToXmlString(true);
            string publickey = oRSA.ToXmlString(false);

            //私钥签名 
            RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
            oRSA3.FromXmlString(privatekey);
            byte[] AOutput = oRSA3.SignData(messagebytes, "SHA1");
            //公钥验证 
            RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
            oRSA4.FromXmlString(publickey);
            bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", AOutput);
        }

        internal static void Test()
        {
            string publickeymk = Getcy("publickeymk.txt");
            string privatekeymk = Getcy("privatekeymk.txt");
            EncryptProcessmk(privatekeymk, Util.GetSystemInfo(), publickeymk);
            DecryptProcessMK();

        }
    }
}